package com.combetter.changxing.bindingconfig;

import android.databinding.BindingAdapter;
import android.databinding.BindingConversion;
import android.support.v7.widget.RecyclerView;

import com.combetter.changxing.adapter.BindingRecyclerViewAdapter;
import com.combetter.changxing.adapter.BindingRecyclerViewAdapterFactory;
import com.combetter.changxing.collections.ItemViewArg;
import com.combetter.changxing.collections.ItemViewSelector;

import java.util.List;

/**
 * Created by Mark.fan on 2018/5/15.
 */

public class BindingRecycleViewAdapterConfig {

    @BindingAdapter( value = {"itemView", "items", "adapter" }, requireAll = false)
    public static <T>void setAdapter(RecyclerView recyclerView, ItemViewArg<T> args, List<T> items, BindingRecyclerViewAdapterFactory factory) {
        BindingRecyclerViewAdapter adapter = (BindingRecyclerViewAdapter) recyclerView.getAdapter();
        if (factory == null) {
            factory = BindingRecyclerViewAdapterFactory.DEFAULT;
        }
        if (adapter == null) {
            adapter = factory.create(recyclerView, args);
            adapter.setItems(items);
            recyclerView.setAdapter(adapter);
        } else {
            adapter.setItems(items);
        }
    }

    @BindingConversion
    public static ItemViewArg toItemViewArg(ItemViewSelector<?> selector) {
        return ItemViewArg.of(selector);
    }

    @BindingConversion
    public static BindingRecyclerViewAdapterFactory toRecyclerViewAdapterFactory(final String className) {
        return new BindingRecyclerViewAdapterFactory() {
            @Override
            public <T> BindingRecyclerViewAdapter<T> create(RecyclerView recyclerView, ItemViewArg<T> arg) {
               return Utils.createClass(className, arg);
            }
        };
    }
}
